package com.zlyx.easy.security.authentication.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import com.zlyx.easy.security.authentication.service.IClientDetailsService;
import com.zlyx.easy.security.authentication.service.IUserDetailsService;

/**
 * <p>
 * 开启权限认证服务
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter implements InitializingBean {

	private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfigurerAdapter.class);

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired(required = false)
	private IUserDetailsService userDetailsService;

	@Autowired(required = false)
	private IClientDetailsService clientDetailsService;

	@Autowired
	private TokenStore tokenStore;

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.withClientDetails(clientDetailsService);
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore)
				.userDetailsService(userDetailsService).reuseRefreshTokens(true);
		endpoints.setClientDetailsService(clientDetailsService);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		CorsConfigurationSource source = request -> {
			CorsConfiguration corsConfiguration = new CorsConfiguration();
			corsConfiguration.addAllowedHeader("*");
			corsConfiguration.addAllowedOrigin(request.getHeader(HttpHeaders.ORIGIN));
			corsConfiguration.addAllowedMethod("*");
			corsConfiguration.setAllowCredentials(true);
			corsConfiguration.setMaxAge(3600L);
			return corsConfiguration;
		};
		security.tokenKeyAccess("permitAll()");
		security.checkTokenAccess("permitAll()");
		security.allowFormAuthenticationForClients();
		security.addTokenEndpointAuthenticationFilter(new CorsFilter(source));
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		logger.info("tokenStore is {}", tokenStore.getClass());
	}
}
